from fastapi import APIRouter, Query, UploadFile, BackgroundTasks
from tortoise.expressions import Q
from app.controllers.marketing.coupons import coupons_controller
from app.controllers.marketing.coupons_rule import coupons_rule_controller
from app.models import CustomerUser, Coupons, CouponsRole
from app.schemas.base import Success, SuccessExtra, Fail
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID

mini_coupons_router = APIRouter()
model_name = "优惠券发放记录"


@mini_coupons_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        is_used: int = Query(0, description=f"使用状态0未使用1已使用2已失效"),
):
    user_id = CTX_USER_ID.get()
    q = Q(is_used=is_used)
    if user_id > 0:
        q &= Q(user_id=user_id)
    total, data = await coupons_controller.do_list(page=page, page_size=page_size, search=q)

    type_objs = await CouponsRole.all()
    name_type_objs = {couponsrole.id: couponsrole for couponsrole in type_objs}

    for item in data:
        couponsrole = name_type_objs.get(item['coupons_id'])
        if couponsrole:
            item['type_name'] = couponsrole.name
            item['remark'] = couponsrole.remark

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)
